package com.sansui.blog.service.impl;

import com.sansui.blog.dao.UserInfoDao;
import com.sansui.blog.pojo.UserInfo;
import com.sansui.blog.service.UserInfoService;
import com.sansui.blog.utils.UploadFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @name: UserInfoServiceImpl
 * @author: Sansui
 * @Software: IDEA
 * @Blog: https://www.cnblogs.com/sansui6/
 * @date: 2022-05-06 21:49
 **/
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Value("${user.avatar-url}")
    private String avatarUrl;


    @Override
    public UserInfo getUserInfoByUserId(String uid) {
        return userInfoDao.getUserInfoByUserId(uid);
    }


    @Transactional
    @Override
    public Map<String, Object> saveUserInfo(UserInfo userInfo,String uid) {
        Map<String,Object> data = new HashMap<>(16);
        try{
            userInfo.setUpdateTime(new Date());
            userInfo.setUid(uid);
//            if(userInfo.getAvatars().indexOf("images")<=-1){
//                //获取修改后的名字，并对头像上传
//                userInfo.setAvatars(avatarUrl+userInfo.getAvatars());
//            }
            userInfoDao.saveUserInfo(userInfo);
            data.put("code",200);
            data.put("msg","保存成功！");
        }catch (Exception e){
            data.put("code",400);
            data.put("msg","修改用户信息失败！");
        }
        return data;
    }


    @Transactional
    @Override
    public Map<String, Object> uploadAvatars(MultipartFile file, String uid){
        Map<String,Object> data = new HashMap<>(16);
        if(!file.isEmpty()){
            try {
                String filename = avatarUrl+UploadFileUtil.upload(file);
                userInfoDao.uploadAvatars(filename,uid);
                data.put("code","200");
                data.put("msg","成功！");
            }catch (IOException e){
                e.printStackTrace();
                data.put("code","400");
                data.put("msg","上传失败！");
            }
        }else{
            data.put("code","400");
            data.put("msg","文件为空！");
        }
        return data;
    }



}
